<template>
  <div class="flex flex-1 gap-2">
    <div class="w-1/4">
      <ElderlyList :status="status" @handleElderlyCurrentChange="getElderlyInfo"/>
    </div>
    
    <div class="flex-1 flex flex-col gap-3">
      <!-- 患者基本信息卡片 -->
      <div class="bg-white rounded-lg p-3">
        <div class="flex justify-between items-center mb-3">
          <div class="text-lg font-bold">患者基本信息</div>
          <div class="space-x-2">
            <el-tag
              v-for="tag in patientTags"
              :key="tag.name"
              :type="tag.type"
              :effect="tag.effect"
              class="mr-2"
            >
              {{ tag.name }}
            </el-tag>
            <el-button type="primary" link @click="showTagDialog = true">
              添加标记
            </el-button>
          </div>
        </div>
        <div class="grid grid-cols-5">
          <div class="flex items-center">
            <span class="text-gray-500">姓名：</span>
            <span>{{ currentPatient.name || '-' }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500">性别：</span>
            <span>{{ currentPatient.gender === '1' ? '男' : '女' }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500">年龄：</span>
            <span>{{ currentPatient.age || '-' }}岁</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500">联系电话：</span>
            <span>{{ currentPatient.phone || '-' }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-500">身份证号：</span>
            <span>{{ currentPatient.idCard || '-' }}</span>
          </div>
        </div>
      </div>

      <!-- 就医历史时间轴 -->
      <div class="flex-1 bg-white rounded-lg p-3">
        <div class="flex justify-between items-center mb-4">
          <div class="text-lg font-bold">就医历史</div>
          <div class="flex items-center gap-4">
            <el-button type="primary" @click="showAddRecordDialog = true">
              添加记录
            </el-button>
            <el-radio-group v-model="timelineFilter" size="small">
              <el-radio-button :value="'all'">全部记录</el-radio-button>
              <el-radio-button :value="'diagnosis'">诊断记录</el-radio-button>
              <el-radio-button :value="'treatment'">治疗方案</el-radio-button>
              <el-radio-button :value="'examination'">检查报告</el-radio-button>
              <el-radio-button :value="'medication'">用药记录</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <el-timeline>
          <el-timeline-item
            v-for="record in filteredMedicalRecords"
            :key="record.id"
            :type="record.type"
            :color="getTimelineColor(record.category)"
            :timestamp="record.time"
            placement="top"
          >
            <el-card class="mb-4">
              <template #header>
                <div class="flex justify-between items-center">
                  <span class="font-bold">{{ record.title }}</span>
                  <el-tag size="small" :type="getTagType(record.category)">
                    {{ getCategoryLabel(record.category) }}
                  </el-tag>
                </div>
              </template>
              <div class="text-sm">
                <div v-if="record.doctor" class="mb-2">
                  <span class="text-gray-500">主治医师：</span>
                  {{ record.doctor }}
                </div>
                <div v-if="record.department" class="mb-2">
                  <span class="text-gray-500">就诊科室：</span>
                  {{ record.department }}
                </div>
                <div class="whitespace-pre-wrap">{{ record.content }}</div>
                <div v-if="record.attachments && record.attachments.length" class="mt-2">
                  <div class="text-gray-500 mb-1">附件：</div>
                  <div class="flex flex-wrap gap-2">
                    <el-link 
                      v-for="file in record.attachments" 
                      :key="file.id"
                      type="primary"
                      @click="previewFile(file)"
                    >
                      {{ file.name }}
                    </el-link>
                  </div>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <!-- 添加标记对话框 -->
    <Drawer
      v-model="showTagDialog"
      title="添加患者标记"
      width="30%"
    >
      <div class="space-y-4">
        <el-checkbox-group v-model="selectedTags">
          <div class="grid grid-cols-2 gap-4">
            <el-checkbox 
              v-for="tag in availableTags"
              :key="tag.value"
              :label="tag.value"
            >
              {{ tag.label }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTagDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAddTags">
            确认
          </el-button>
        </span>
      </template>
    </Drawer>

    <!-- 添加记录对话框 -->
    <Drawer
      v-model="showAddRecordDialog"
      :title="editingRecord.id ? '编辑记录' : '添加记录'"
      width="50%"
    >
      <el-form :model="editingRecord" ref="recordFormRef" :rules="recordRules" label-width="100px">
        <el-form-item label="记录类型" prop="category">
          <el-select v-model="editingRecord.category" placeholder="请选择记录类型" class="w-full">
            <el-option label="诊断记录" value="diagnosis" />
            <el-option label="治疗方案" value="treatment" />
            <el-option label="检查报告" value="examination" />
            <el-option label="用药记录" value="medication" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="editingRecord.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="就诊时间" prop="time">
          <el-date-picker
            v-model="editingRecord.time"
            type="datetime"
            placeholder="请选择就诊时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="主治医师" prop="doctor">
          <el-input v-model="editingRecord.doctor" placeholder="请输入主治医师姓名" />
        </el-form-item>
        <el-form-item label="就诊科室" prop="department">
          <el-input v-model="editingRecord.department" placeholder="请输入就诊科室" />
        </el-form-item>
        <el-form-item label="详细内容" prop="content">
          <el-input
            v-model="editingRecord.content"
            type="textarea"
            :rows="4"
            placeholder="请输入详细内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="editingRecord.attachments"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip text-xs text-gray-500">
                支持 jpg/png/pdf 文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddRecordDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRecord">
            保存
          </el-button>
        </span>
      </template>
    </Drawer>
  </div>
</template>

<script setup>
import ElderlyList from '@/components/common/elderlyList.vue';
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import Drawer from '@/components/common/Drawer.vue';
const status = ref('14');
const currentPatient = ref({});

// 获取老人信息
const getElderlyInfo = (row) => {
  console.log(row);
  currentPatient.value = row;
  // 这里应该调用获取患者档案信息的接口
  loadPatientRecords(row.id);
};

// 患者标记
const patientTags = ref([
  { name: '慢性病患者', type: 'warning', effect: 'dark' },
  { name: '高血压', type: 'danger', effect: 'light' },
  { name: '糖尿病', type: 'danger', effect: 'light' }
]);

// 可选标记
const availableTags = [
  { label: '慢性病患者', value: 'chronic' },
  { label: '手术患者', value: 'surgery' },
  { label: '高血压', value: 'hypertension' },
  { label: '糖尿病', value: 'diabetes' },
  { label: '心脏病', value: 'heart' },
  { label: '过敏体质', value: 'allergy' },
  { label: '重点关注', value: 'focus' },
  { label: '需要随访', value: 'follow' }
];

// 时间轴筛选
const timelineFilter = ref('all');

// 就医记录
const medicalRecords = ref([]);

// 加载患者就医记录
const loadPatientRecords = (patientId) => {
  // 这里应该调用后端API获取就医记录
  // 以下为模拟数据
  medicalRecords.value = [
    {
      id: 1,
      category: 'diagnosis',
      type: 'primary',
      time: '2024-01-15 09:30',
      title: '初次问诊',
      doctor: '李医生',
      department: '内科',
      content: '患者主诉：近期经常感到头晕、乏力。\n血压：150/95mmHg\n建议进行进一步检查。',
      attachments: []
    },
    {
      id: 2,
      category: 'examination',
      type: 'success',
      time: '2024-01-15 10:30',
      title: '血常规检查',
      doctor: '王医生',
      department: '检验科',
      content: '血常规各项指标正常。',
      attachments: [
        { id: 1, name: '血常规检查报告.pdf' }
      ]
    }
  ];
};

// 计算筛选后的就医记录
const filteredMedicalRecords = computed(() => {
  if (timelineFilter.value === 'all') {
    return medicalRecords.value;
  }
  return medicalRecords.value.filter(record => record.category === timelineFilter.value);
});

// 获取时间轴颜色
const getTimelineColor = (category) => {
  const colors = {
    diagnosis: '#409EFF',
    examination: '#67C23A',
    treatment: '#E6A23C',
    medication: '#909399'
  };
  return colors[category] || '#409EFF';
};

// 获取标签类型
const getTagType = (category) => {
  const types = {
    diagnosis: 'primary',
    examination: 'success',
    treatment: 'warning',
    medication: 'info'
  };
  return types[category] || 'primary';
};

// 获取分类标签文本
const getCategoryLabel = (category) => {
  const labels = {
    diagnosis: '诊断记录',
    examination: '检查报告',
    treatment: '治疗方案',
    medication: '用药记录'
  };
  return labels[category] || '';
};

// 标记相关
const showTagDialog = ref(false);
const selectedTags = ref([]);

// 添加标记
const handleAddTags = () => {
  // 这里应该调用后端API保存标记
  ElMessage.success('添加标记成功');
  showTagDialog.value = false;
};

// 预览文件
const previewFile = (file) => {
  // 这里应该调用文件预览功能
  ElMessage.info('预览文件：' + file.name);
};

// 添加记录相关
const showAddRecordDialog = ref(false);
const recordFormRef = ref();
const editingRecord = ref({
  category: '',
  title: '',
  time: '',
  doctor: '',
  department: '',
  content: '',
  attachments: []
});

// 表单验证规则
const recordRules = {
  category: [{ required: true, message: '请选择记录类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  time: [{ required: true, message: '请选择就诊时间', trigger: 'change' }],
  doctor: [{ required: true, message: '请输入主治医师姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请输入就诊科室', trigger: 'blur' }],
  content: [{ required: true, message: '请输入详细内容', trigger: 'blur' }]
};

// 处理文件上传
const handleFileChange = (file, fileList) => {
  editingRecord.value.attachments = fileList;
};

// 保存记录
const handleSaveRecord = async () => {
  if (!recordFormRef.value) return;
  
  await recordFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 这里应该调用后端API保存记录
      const newRecord = {
        ...editingRecord.value,
        id: Date.now(), // 临时ID，实际应该由后端生成
        type: getTagType(editingRecord.value.category),
        attachments: editingRecord.value.attachments.map(file => ({
          id: file.uid,
          name: file.name
        }))
      };

      if (editingRecord.value.id) {
        // 更新现有记录
        const index = medicalRecords.value.findIndex(r => r.id === editingRecord.value.id);
        if (index !== -1) {
          medicalRecords.value[index] = newRecord;
        }
      } else {
        // 添加新记录
        medicalRecords.value.unshift(newRecord);
      }

      ElMessage.success('保存成功');
      showAddRecordDialog.value = false;
      resetEditingRecord();
    } else {
      console.log('validation failed', fields);
    }
  });
};

// 重置编辑表单
const resetEditingRecord = () => {
  editingRecord.value = {
    category: '',
    title: '',
    time: '',
    doctor: '',
    department: '',
    content: '',
    attachments: []
  };
};

// 编辑记录
const editRecord = (record) => {
  editingRecord.value = { ...record };
  showAddRecordDialog.value = true;
};
</script>

<style scoped>
:deep(.el-timeline-item__node--primary) {
  background-color: var(--el-color-primary);
}

:deep(.el-timeline-item__node--success) {
  background-color: var(--el-color-success);
}

:deep(.el-timeline-item__node--warning) {
  background-color: var(--el-color-warning);
}

:deep(.el-timeline-item__node--info) {
  background-color: var(--el-color-info);
}

:deep(.el-upload-list) {
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}
</style>

